<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container" style="padding-bottom: 50px; margin: 0">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <!-- <px-button style="margin-top: 0" type="primary">抄表任务</px-button> -->

      <span>
        <px-form-item label="系统" style="width: 270px !important">
          <px-tree-select
            v-model="queryParams.systemCode"
            clearable
            style="width: 100%"
            placeholder="请选择设备系统（树状图）"
            :props="defaultProps"
            :data="systemList"
            filterable
            @node-click="nodeClick"
          />
        </px-form-item>
        <px-form-item label="设备" style="width: 270px !important">
          <!-- <px-input v-model="queryParams.eqpId" style="width: 220px" placeholder="请输入" clearable /> -->
          <px-select
            v-model="queryParams.eqpId"
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            clearable
            :remote-method="remoteMethod"
            placeholder="请选择"
            style="width: 220px"
          >
            <px-option v-for="dict in eqpList" :key="dict.eqpId" :label="`${dict.eqpName}(${dict.eqpId})`" :value="dict.eqpId" />
          </px-select>
        </px-form-item>
        <px-form-item label="仪表" style="width: 270px !important">
          <!-- <px-input v-model="queryParams.instrumentId" style="width: 220px" placeholder="请输入" clearable /> -->
          <px-select
            v-model="queryParams.instrumentId"
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            clearable
            :remote-method="remoteMethod12"
            placeholder="请选择"
            style="width: 220px"
          >
            <px-option v-for="dict in instrumenList" :key="dict.eqpId" :label="`${dict.eqpName}(${dict.eqpId})`" :value="dict.eqpId" />
          </px-select>
        </px-form-item>
        <px-form-item label="抄表项" style="width: 270px !important">
          <px-input v-model="queryParams.itemName" style="width: 220px" placeholder="请输入" clearable />
          <!-- <px-select v-model="queryParams.instrumentId" clearable placeholder="请选择" style="width: 220px" filterable>
            <px-option v-for="dict in instrumenList" :key="dict.eqpId" :label="dict.eqpName" :value="dict.eqpId" />
          </px-select> -->
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">查询</px-button>
        <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
      </span>
      <!-- <px-button style="margin-top: 0" type="primary" plain @click="exportToExcel()">导出</px-button> -->
    </px-form>
    <px-row :gutter="10" class="mb8">
      <!-- <px-col :span="1.5">
        <px-button type="primary" icon="" @click="handleAdd">新增</px-button>
      </px-col> -->
      <!-- <px-col :span="1.5">
        <px-button type="primary" plain icon="" @click="handleExport">导入</px-button>
      </px-col> -->
      <px-col v-if="classcode == 'WATER'" :span="1.5">
        <px-button v-has="'METER_READING_HISTORY_WATER_IMPORT'" type="primary" plain icon="" @click="handleImport">导入</px-button>
      </px-col>
      <px-col v-if="classcode == 'MACHINE'" :span="1.5">
        <px-button v-has="'METER_READING_HISTORY_MACHINE_IMPORT'" type="primary" plain icon="" @click="handleImport">导入</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button
          v-if="classcode == 'WATER'"
          v-has="'METER_READING_WATER_EXPORT'"
          type="primary"
          :disabled="multiple"
          plain
          icon=""
          @click="handleExport"
          >导出</px-button
        >
        <px-button
          v-if="classcode == 'MACHINE'"
          v-has="'METER_READING_MACHINE_EXPORT'"
          type="primary"
          :disabled="multiple"
          plain
          icon=""
          @click="handleExport"
          >导出</px-button
        >
        <px-button
          v-if="classcode == 'GAS'"
          v-has="'METER_READING_GAS_EXPORT'"
          type="primary"
          :disabled="multiple"
          plain
          icon=""
          @click="handleExport"
          >导出</px-button
        >
        <px-button
          v-if="classcode == 'ELECTRICTITY'"
          v-has="'METER_READING_ELECTRICTITY_EXPORT'"
          type="primary"
          :disabled="multiple"
          plain
          icon=""
          @click="handleExport"
          >导出</px-button
        >
      </px-col>
      <px-dialog v-model="dialogVisible" draggable clickHideContent title="导入数据" :width="600" :before-close="handelClose">
        <div class="import-bottle">
          <div class="import-bottle-upload">
            <div class="import-bottle-title">
              上传前请先
              <!-- <span class="download" @click="downloadFn"> 下载模板 </span> -->
              <a :href="fsxlsx" download="仪表导入模板.xlsx"><span class="download"> 下载模板 </span></a>
              ，填写完成后导入数据
            </div>
            <importFiles
              ref="dialogSuccess"
              v-model="importFile"
              :upfileid="upfileid"
              :isNotImmediateUpload="false"
              :uploadApi="meterReadingRecordimport"
              @submit="submitHandler"
            />
          </div>
        </div>
      </px-dialog>
      <!-- <px-col :span="1.5">
        <px-button v-has="'CommonEquipListDelete'" type="danger" plain icon="" :disabled="multiple" @click="handleDelete">删除</px-button>
      </px-col> -->
    </px-row>
    <px-table
      v-loading="loading"
      class="readingtable"
      :data="typeList"
      show-overflow-tooltip
      height="calc(100vh - 339px)"
      border
      :cell-style="cellStyle"
      @selection-change="handleSelectionChange"
    >
      <px-table-column type="selection" width="40" />
      <px-table-column label="序号" width="80" align="center" fixed="left">
        <template #default="{ $index }">
          {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </px-table-column>
      <px-table-column label="系统" prop="name">
        <template #default="scope">
          <span>{{ scope.row.systemName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="设备名称" prop="name">
        <template #default="scope">
          <span>{{ scope.row.eqpName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="设备编号" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.eqpId }}</span>
        </template>
      </px-table-column>
      <px-table-column label="抄表项" prop="specValue">
        <template #default="scope">
          <span>{{ scope.row.itemName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="仪表编号" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.instrumentId }}</span>
        </template>
      </px-table-column>
      <px-table-column label="SPEC值" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.uslValue }}~{{ scope.row.lslValue }}</span>
        </template>
      </px-table-column>
      <px-table-column label="单位" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </px-table-column>
      <px-table-column label="抄表方式" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.type == 0 ? "自动抄表" : "手动抄表" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="抄表数值" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.value }}</span>
        </template>
      </px-table-column>
      <px-table-column label="抄表时间" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.ctime }}</span>
        </template>
      </px-table-column>
      <px-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <px-button v-if="classcode == 'WATER'" v-has="'METER_READING_WATER_EDITOR'" link type="primary" @click="handleEditor(scope.row)">
            <px-tooltip class="box-item" content="修正" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'WATER'" v-has="'METER_READING_WATER_LIST_ADD'" link type="primary" @click="handleRowAdd(scope.row)">
            <px-tooltip class="box-item" content="新增" placement="top">
              <px-icon><Plus /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'WATER'" v-has="'METER_READING_WATER_HISTORY'" link type="primary" @click="handleHistory(scope.row)"
            ><px-tooltip class="box-item" content="历史" placement="top">
              <px-icon><Histogram /></px-icon> </px-tooltip
          ></px-button>

          <px-button v-if="classcode == 'GAS'" v-has="'METER_READING_GAS_EDITOR'" link type="primary" @click="handleEditor(scope.row)">
            <px-tooltip class="box-item" content="修正" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'GAS'" v-has="'METER_READING_GAS_LIST_ADD'" link type="primary" @click="handleRowAdd(scope.row)">
            <px-tooltip class="box-item" content="新增" placement="top">
              <px-icon><Plus /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'GAS'" v-has="'METER_READING_GAS_HISTORY'" link type="primary" @click="handleHistory(scope.row)"
            ><px-tooltip class="box-item" content="历史" placement="top">
              <px-icon><Histogram /></px-icon> </px-tooltip
          ></px-button>

          <px-button v-if="classcode == 'MACHINE'" v-has="'METER_READING_MACHINE_EDITOR'" link type="primary" @click="handleEditor(scope.row)">
            <px-tooltip class="box-item" content="修正" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'MACHINE'" v-has="'METER_READING_MACHINE_LIST_ADD'" link type="primary" @click="handleRowAdd(scope.row)">
            <px-tooltip class="box-item" content="新增" placement="top">
              <px-icon><Plus /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="classcode == 'MACHINE'" v-has="'METER_READING_MACHINE_HISTORY'" link type="primary" @click="handleHistory(scope.row)"
            ><px-tooltip class="box-item" content="历史" placement="top">
              <px-icon><Histogram /></px-icon> </px-tooltip
          ></px-button>

          <px-button
            v-if="classcode == 'ELECTRICTITY'"
            v-has="'METER_READING_ELECTRICTITY_EDITOR'"
            link
            type="primary"
            @click="handleEditor(scope.row)"
          >
            <px-tooltip class="box-item" content="修正" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button
            v-if="classcode == 'ELECTRICTITY'"
            v-has="'METER_READING_ELECTRICTITY_LIST_ADD'"
            link
            type="primary"
            @click="handleRowAdd(scope.row)"
          >
            <px-tooltip class="box-item" content="新增" placement="top">
              <px-icon><Plus /></px-icon> </px-tooltip
          ></px-button>
          <px-button
            v-if="classcode == 'ELECTRICTITY'"
            v-has="'METER_READING_ELECTRICTITY_HISTORY'"
            link
            type="primary"
            @click="handleHistory(scope.row)"
            ><px-tooltip class="box-item" content="历史" placement="top">
              <px-icon><Histogram /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>
    <pagination
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />
    <px-dialog v-model="addVisible" draggable clickHideContent width="500" :title="buttonTitle" append-to-body align-center>
      <px-form v-show="showSearch" ref="detailruleFormRef" :model="addForm" :rules="rules2" :inline="true" label-width="120px">
        <px-row>
          <px-col :span="24">
            <px-form-item style="width: 400px !important" label="抄表数值" prop="value">
              <px-input-number v-model="addForm.value" controls-position="right" style="width: 280px" placeholder="请输入" clearable />
            </px-form-item>
            <px-form-item style="width: 400px !important" label="抄表时间" prop="ctime">
              <px-date-picker
                v-model="addForm.ctime"
                :disabled="buttonTitle != '新增'"
                style="width: 280px"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="addVisible = false">取消</px-button>
          <px-button type="primary" @click="addeqp(detailruleFormRef)"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>

    <px-dialog v-model="exportVisible" draggable clickHideContent width="600" title="导出" append-to-body align-center>
      <px-form v-show="showSearch" ref="exportFormRef" :model="exportForm" :rules="rules2" :inline="true" label-width="120px">
        <px-row>
          <px-col :span="24">
            <px-form-item label="导出时间范围" style="width: 440px !important">
              <px-date-picker
                v-model="exportForm.exportTime"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="defaultTime"
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="exportVisible = false">取消</px-button>
          <px-button type="primary" @click="handleExportList"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>

    <px-dialog v-model="historyVisible" draggable clickHideContent width="1200" title="历史记录" append-to-body align-center>
      <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
        <!-- <px-button style="margin-top: 0" type="primary">抄表任务</px-button> -->

        <span>
          <px-form-item label="时间范围" style="width: 440px !important">
            <px-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
            />
          </px-form-item>
          <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQueryhistory()">查询</px-button>
          <px-button style="margin-top: -17px" icon="" @click="resetQueryhistory()">重置</px-button>
        </span>
      </px-form>
      <historyLine :chartlist="barchartvalue" style="width: 100%; height: 300px" :width="'100%'" :height="'250px'" />
      <px-button style="float: right; margin-bottom: 16px" type="primary" plain icon="" @click="handleExporthistory">导出</px-button>
      <px-table :data="barchartvalue" show-overflow-tooltip border>
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column label="系统" prop="name">
          <template #default="scope">
            <span>{{ scope.row.systemName }}</span>
          </template>
        </px-table-column>

        <px-table-column label="设备名称" prop="name">
          <template #default="scope">
            <span>{{ scope.row.eqpName }}</span>
          </template>
        </px-table-column>

        <px-table-column label="设备编号" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.eqpId }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表项" prop="specValue">
          <template #default="scope">
            <span>{{ scope.row.itemName }}</span>
          </template>
        </px-table-column>
        <px-table-column label="仪表编号" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.instrumentId }}</span>
          </template>
        </px-table-column>
        <px-table-column label="SPEC值" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.uslValue }}~{{ scope.row.lslValue }}</span>
          </template>
        </px-table-column>
        <px-table-column label="单位" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.unit }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表方式" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.type == 0 ? "自动抄表" : "手动抄表" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表数值" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.value }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表时间" prop="meterName">
          <template #default="scope">
            <span>{{ scope.row.ctime }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" align="center" width="80">
          <template #default="scope">
            <px-button v-if="scope.row.status != 'INVALID'" link type="primary" @click="handleEditor2(scope.row)">
              <px-tooltip class="box-item" content="修正" placement="top">
                <px-icon>
                  <EditPen />
                </px-icon> </px-tooltip
            ></px-button>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <!-- <template #footer>
        <span class="dialog-footer">
          <px-button @click="historyVisible = false">取消</px-button>
          <px-button type="primary" @click="addeqp(detailruleFormRef)"> 确定 </px-button>
        </span>
      </template> -->
    </px-dialog>

    <px-dialog v-model="FileVisible" draggable clickHideContent width="1100" title="导入结果" append-to-body align-center>
      <px-table :data="fileresultList" show-overflow-tooltip border>
        <px-table-column label="行数" prop="name">
          <template #default="scope">
            <span>{{ scope.row.rowIndex }}</span>
          </template>
        </px-table-column>
        <px-table-column label="导入结果" prop="name">
          <template #default="scope">
            <span v-if="scope.row.success == false" style="color: #ef4444">{{ scope.row.message }}</span>
            <span v-else style="color: #10b981">{{ scope.row.message }}</span>
          </template>
        </px-table-column>
      </px-table>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="FileVisible = false">关闭</px-button>
          <!-- <px-button type="primary" @click="addeqp(detailruleFormRef)"> 确定 </px-button> -->
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});

// import { router } from "@/router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { queryEquipLedger, querySystemSelect } from "@/api/equip/archive";
import historyLine from "./historyLine.vue";
import {
  meterreadingqueryList,
  meterreadingdelete,
  systemCategoryqueryListTree,
  meterreadingadd,
  meterreadingupdate,
  meterreadingqueryById,
  eqpRelqueryEqpRelByEqpId,
  measuregetMeasure,
  meterReadingRecordvalidate,
  meterReadingRecordupdate,
  meterReadingRecordadd,
  meterReadingRecordqueryAll,
  meterReadingRecordimport
} from "@/api/water/watchMeterReading";
import { queryReadingModifyHistory } from "@/api/waterBalance";
import { pageMeasureList } from "@/api/system/measure";
import importFiles from "./importFiles.vue";
const props = defineProps({
  classcode: {
    type: String,
    default: ""
  }
});
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const total = ref(0);
const dateRange = ref([]);
const eqpList = ref([]);
const instrumenList = ref([]);
const systemList = ref([]);
const specIdList = ref([]);
const barchartvalue = ref([]);
const handleQueryhistory = () => {
  meterReadingRecordqueryAll({
    itemFormId: selectrow.value.id,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  }).then(res => {
    console.log(res);
    barchartvalue.value = res;
  });
};
const remoteMethod = quary => {
  console.log(quary);
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: quary,
    categoryId: null,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: queryParams.value.systemCode ? queryParams.value.systemCode : "",
    systemCodes: queryParams.value.systemCode ? [queryParams.value.systemCode] : [],
    positionCodes: []
  }).then(res => {
    console.log(res);
    eqpList.value = res.data;
  });
};
const remoteMethod12 = quary => {
  console.log(quary);
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: quary,
    categoryId: 35,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: queryParams.value.systemCode ? queryParams.value.systemCode : "",
    systemCodes: queryParams.value.systemCode ? [queryParams.value.systemCode] : [],
    positionCodes: []
  }).then(res => {
    console.log(res);
    instrumenList.value = res.data;
  });
};
const nodeClick = (e1emData, nodeData) => {
  console.log(e1emData, nodeData);
  // selectTree.value = e1emData;
  if (e1emData.name != addForm.value.systemName) {
    addForm.value.eqpId = "";
    addForm.value.instrumentId = "";
  }
  addForm.value.systemName = e1emData.name;
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: "",
    categoryId: null,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: e1emData.code,
    systemCodes: [e1emData.code],
    positionCodes: []
  }).then(res => {
    console.log(res);
    eqpList.value = res.data;
  });
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: "",
    categoryId: 35,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: e1emData.code,
    systemCodes: [e1emData.code],
    positionCodes: []
  }).then(res => {
    console.log(res);
    instrumenList.value = res.data;
  });
};
const resetQueryhistory = () => {
  const end = new Date();
  // end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  const start2 = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  console.log(props.classcode);
  dateRange.value = [formatDate(start), formatDate(end)];
  meterReadingRecordqueryAll({
    itemFormId: selectrow.value.id,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  }).then(res => {
    console.log(res);
    barchartvalue.value = res;
  });
};
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
onMounted(() => {
  upfileid.value = props.classcode;
  fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/仪表抄表数据导入模板.xlsx`);
  const end = new Date();
  // end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  const start2 = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  console.log(props.classcode);
  dateRange.value = [formatDate(start), formatDate(end)];
  if (localStorage.getItem("chukuList")) {
  }
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: "",
    categoryId: null,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: "",
    systemCodes: [],
    positionCodes: []
  }).then(res => {
    console.log(res);
    eqpList.value = res.data;
  });
  queryEquipLedger({
    pageNum: 1,
    pageSize: 9999,
    isAsc: "desc",
    orderByColumn: "updateTime",
    value: "",
    categoryId: 35,
    typeId: null,
    modelId: null,
    className: props.classcode,
    systemCode: "",
    systemCodes: [],
    positionCodes: []
  }).then(res => {
    console.log(res);
    instrumenList.value = res.data;
  });
  systemCategoryqueryListTree({
    className: props.classcode
  }).then(res => {
    systemList.value = res;
  });
  pageMeasureList({
    measureName: "",
    tagCode: "",
    measureCode: "",
    isNeedCalculate: "",
    measureTypeCode: "",
    createBy: "",
    className: props.classcode,
    measureSource: "",
    isMaintain: "",
    pageNum: 1,
    pageSize: 9999,
    systemCode: ""
  }).then(res => {
    console.log(res);
    specIdList.value = res.data;
  });
});
const selectrow2 = ref({});
const handleEditor = row => {
  console.log(row);
  if (row.ctime) {
    buttonTitle.value = "修正";
    detailruleFormRef.value?.resetFields();
    addVisible.value = true;
    selectrow.value = row;
    addForm.value.value = row.value;
    addForm.value.ctime = row.ctime;
  } else {
    handleRowAdd(row);
  }
};
const handleEditor2 = row => {
  console.log(row);
  buttonTitle.value = "历史修正";
  detailruleFormRef.value?.resetFields();
  addVisible.value = true;
  selectrow2.value = row;
  addForm.value.value = row.value;
  addForm.value.ctime = row.ctime;
  // meterreadingqueryById({
  //   id: val
  // }).then(res => {
  //   console.log(res);
  //   addVisible.value = true;
  //   addForm.value = res;
  // });
};
const fileresultList = ref([]);
const dialogVisible = ref(false);
const FileVisible = ref(false);
const fsxlsx = ref("");
const upfileid = ref("");
const importFile = ref("");
function handleExport() {
  exportVisible.value = true;
  exportForm.value.exportTime = [];
}
const handleImport = () => {
  dialogVisible.value = true;
  fileresultList.value = [];
  FileVisible.value = false;
};
const submitHandler = val => {
  console.log(val);
  let detailsSuccess = val.details.filter(item => item.success);
  if (detailsSuccess.length > 0) {
    FileVisible.value = true;
    fileresultList.value = val.details;
    getList();
  } else {
    FileVisible.value = true;
    fileresultList.value = val.details;
    getList();
    PxMessage({
      message: "数据导入失败",
      type: "error"
    });
  }
};

const handleRowAdd = row => {
  console.log(row);
  buttonTitle.value = "新增";
  addVisible.value = true;
  selectrow.value = row;
  addForm.value.value = null;
  addForm.value.ctime = "";
  detailruleFormRef.value?.resetFields();
};
const handleHistory = row => {
  console.log(row);
  barchartvalue.value = [];
  historyVisible.value = true;
  selectrow.value = row;
  meterReadingRecordqueryAll({
    itemFormId: row.id,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  }).then(res => {
    console.log(res);
    barchartvalue.value = res;
  });
};
const addeqp = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      console.log(111);

      if (buttonTitle.value == "修正") {
        console.log(selectrow.value);
        if (selectrow.value.recordId) {
          let parmas = {
            id: selectrow.value.recordId,
            ctime: addForm.value.ctime,
            value: addForm.value.value
          };
          meterReadingRecordupdate(parmas).then(res => {
            PxMessage({
              message: `修改成功`,
              type: "success"
            });
            addVisible.value = false;
            getList();
          });
        } else {
          let parmas = {
            itemFormId: selectrow.value.id,
            ctime: addForm.value.ctime,
            value: addForm.value.value
          };

          meterReadingRecordadd(parmas).then(res => {
            PxMessage({
              message: `修改成功`,
              type: "success"
            });
            addVisible.value = false;
            getList();
          });
        }
      } else {
        if (buttonTitle.value == "历史修正") {
          let parmas = {
            id: selectrow2.value.id,
            ctime: addForm.value.ctime,
            value: addForm.value.value
          };
          meterReadingRecordupdate(parmas).then(res => {
            PxMessage({
              message: `修改成功`,
              type: "success"
            });
            addVisible.value = false;
            handleHistory(selectrow.value);
            getList();
          });
        } else {
          let parmas = {
            itemFormId: selectrow.value.id,
            ctime: addForm.value.ctime,
            value: addForm.value.value
          };
          meterReadingRecordvalidate(parmas).then(res => {
            console.log(res);
            if (res.success == false) {
              PxMessageBox.confirm(`${res.msg}`, "温馨提示", {
                confirmButtonText: "替换原值",
                cancelButtonText: "取消",
                type: "warning",
                draggable: true
              })
                .then(async () => {
                  meterReadingRecordadd(parmas).then(res => {
                    PxMessage({
                      message: `修改成功`,
                      type: "success"
                    });
                    addVisible.value = false;
                    getList();
                  });
                })
                .catch(() => {});
            } else {
              meterReadingRecordadd(parmas).then(res => {
                PxMessage({
                  message: `新增成功`,
                  type: "success"
                });
                addVisible.value = false;
                getList();
              });
            }
          });
        }
      }
    }
  });
};
const geteqpRelqueryEqpRelByEqpId = val => {};
const detailruleFormRef = ref();
const exportFormRef = ref();
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
const { proxy }: any = getCurrentInstance();
const exportVisible = ref(false);

function handleExportList() {
  if (exportForm.value.exportTime.length > 0) {
    proxy.download("post", "/operation/api/v1/meterReadingRecord/export", {
      itemFormIds: ids.value,
      startTime: exportForm.value.exportTime[0],
      endTime: exportForm.value.exportTime[1]
    });
    exportVisible.value = false;
  } else {
    PxMessage({
      message: `请选择导出时间`,
      type: "error"
    });
  }
}
function handleExporthistory() {
  console.log(ids.value);
  proxy.download("post", "/operation/api/v1/meterReadingRecord/export", {
    itemFormIds: [selectrow.value.id],
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  });
}
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  console.log(val2, val3, val4);
  // formValue.value.className = val2;
  // formValue.value.systemCode = val3;
  // systemCodes.value = val4;
  // formRef.value?.resetFields(["categoryId", "typeId", "modelId"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  console.log(val2, val);
  queryParams.value.systemCode = val;
  // queryParams.systemCode = val2;
  // formRef.value?.resetFields(["categoryId", "typeId", "modelId"]);
};
// 系统组件值改变触发
const clearSystem = val => {
  console.log(val);
  queryParams.value.systemCode = "";
  // formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId"]);
};
const typeList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const addVisible = ref(false);
const addVisible2 = ref(false);
const tsspanshow1 = ref(false);
const tsspanshow2 = ref(false);
const historyVisible = ref(false);
// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: {},
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  wasteUnitoptions: [
    {
      value: "克",
      label: "克"
    },
    {
      value: "千克",
      label: "千克"
    },
    {
      value: "吨",
      label: "吨"
    }
  ],
  typevalueList: [
    {
      name: "自动抄表",
      value: 0
    },
    {
      name: "手动抄表",
      value: 1
    }
  ],
  photoStatusFlag: false,
  fileStatusFlag: false,
  SpcAnalysis: [],
  equipdata: {
    id: null,
    classCode: props.classcode,
    itemName: "",
    itemCode: null,
    specId: "",
    specName: "",
    systemCode: "",
    systemName: "",
    eqpId: "T-",
    eqpName: "",
    instrumentId: "-506",
    instrumentName: "",
    instrumentShowName: null,
    uslValue: null,
    lslValue: null,
    unit: "",
    type: null,
    value: null,
    ctime: null,
    updateTime: "",
    createTime: "",
    status: "",
    synTime: null
  },
  addForm: {
    value: "",
    ctime: ""
  },
  exportForm: {
    exportTime: []
  },
  rules1: {
    value: [{ required: true, message: "抄表数值不能为空", trigger: "blur" }]
  },
  rules2: {
    value: [{ required: true, message: "抄表数值不能为空", trigger: "blur" }],
    ctime: [{ required: true, message: "抄表时间不能为空", trigger: "blur" }]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    classCode: props.classcode,
    itemName: null,
    specId: null,
    systemCode: null,
    eqpId: null,
    instrumentId: null,
    startTime: null,
    endTime: null
  },
  rules: {
    name: [{ required: true, message: "不能为空", trigger: "blur" }],
    serialNumber: [{ required: true, message: "不能为空", trigger: "blur" }],
    category: [{ required: true, message: "不能为空", trigger: "change" }],
    activityLevelUnit: [{ required: true, message: "不能为空", trigger: "change" }],
    emissionFactorName: [{ required: true, message: "不能为空", trigger: "blur" }],
    value: [{ required: true, message: "不能为空", trigger: "blur" }],
    factorSource: [{ required: true, message: "不能为空", trigger: "blur" }],
    releaseYear: [{ required: true, message: "不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "不能为空", trigger: "blur" }],
    unitConversionRatio: [{ required: true, message: "不能为空", trigger: "blur" }],
    emissionCategory: [{ required: true, message: "不能为空", trigger: "change" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  levelUnitList: [],
  energyList: [],
  categoryTypeList: [],
  SourceList: [],
  selectrow: null,
  nameSpanMap: {},
  oldList: [],
  oldList2: [],
  ModifyHistoryList: []
});
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 5) {
    if (row.modifyValue !== null) {
      if (row.modifyValue > row.readingValue) {
        return { background: "#FFDADA !important" };
      }
      if (row.modifyValue < row.readingValue) {
        return { background: "#DFFFEA !important" };
      }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const {
  exportForm,
  selectRukuList,
  queryParams,
  addForm,
  rules2,
  form,
  equipdata,
  rukuList,
  selectrow,
  nameSpanMap,
  oldList,
  oldList2,
  typevalueList,
  ModifyHistoryList,
  SpcAnalysis
} = toRefs(data);
function getList() {
  loading.value = true;
  meterreadingqueryList(queryParams.value)
    .then(res => {
      typeList.value = res.data;
      loading.value = false;
      total.value = res.total;
    })
    .catch(() => {
      loading.value = false;
    });
}

/** 取消按钮 */

/** 表单重置 */

/** 搜索按钮操作 */
function handleQuery(type) {
  getList();
}

function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    classCode: props.classcode,
    itemName: null,
    specId: null,
    systemCode: null,
    eqpId: null,
    instrumentId: null,
    startTime: null,
    endTime: null
  };
  getList();
}
const specIdchange = val => {
  console.log(val);
  if (val) {
    addForm.value.unit = specIdList.value.filter(item => item.measureCode == val)[0].measureUnit;
    addForm.value.specName = specIdList.value.filter(item => item.measureCode == val)[0].measureName;
  }
};
const eqpIdchange = val => {
  if (val) {
    addForm.value.eqpName = eqpList.value.filter(item => item.eqpId == val)[0].eqpName;
  }
};
const instrumentIdchange = val => {
  if (val) {
    addForm.value.instrumentName = instrumenList.value.filter(item => item.eqpId == val)[0].eqpName;
  }
};
/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  addForm.value = {
    id: "",
    classCode: props.classcode,
    itemName: "",
    itemCode: "",
    specId: "",
    specName: "",
    systemCode: "",
    systemName: "",
    instrumentId: "",
    instrumentName: "",
    eqpId: "",
    eqpName: "",
    uslValue: null,
    lslValue: null,
    unit: "",
    type: null
  };
}
// const handleDetail = async val => {
//   historyVisible.value = true;
//   const data = await queryReadingModifyHistory({ pointNumber: val, readingDate: queryParams.value.queryDate });
//   console.log(data);
//   ModifyHistoryList.value = data.historyDTO;
//   // equipdata.value = data;
// };
getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 266px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table .cell) {
  line-height: 30px;
  vertical-align: middle;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.modifyValue {
  display: inline-block;
  width: calc(100% - 30px);
}

.valueColor1 {
  color: #3b82f6;
}

.valueColor2 {
  color: #f59e0b;
}

.valueColor3 {
  color: #10b981;
}

#print-content {
  position: absolute;
  left: -20000px;
}

#print-img {
  position: absolute;
  left: -20000px;
  width: 800px;
}

.tsspan {
  display: inline-block;
  margin: 0 0 12px 125px;
  color: red;
}

.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
      cursor: pointer;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}
</style>
